/*
 * App Channel Config API - 应用商户渠道配置API
 * 集成统一渠道配置(unifiedchannelconfig)
 *
 * 基于服务商渠道配置API改造，支持应用商户渠道配置
 * 配置类型：APP_MERCHANT_CHANNEL (config_type = 2)
 * 拥有者类型：APPLICATION (owner_type = 2)
 */

import {
  apiUnifiedChannelConfigFetchList,
  apiUnifiedChannelConfigEdit,
  apiUnifiedChannelConfigCreateUcc
} from '@/miaoma/unifiedchannelconfig/api'

export interface AppChannelConfigData {
  configId?: string // 可选，由后端生成
  configType: number // 2: APP_MERCHANT_CHANNEL
  ownerId: string // appId
  ownerType: number // 2: APPLICATION
  channelCode: string
  productCode?: string
  connectMode?: number // 应用的原始连接模式：1-DIRECT, 2-INDIRECT
  configData: string // JSON string of the actual config
  enabled?: boolean
  createdTime?: string
  updatedTime?: string
}

export interface AppChannelConfigQueryParams {
  appId: string
  channelCode?: string
  connectMode?: number
  enabled?: boolean
}

/**
 * 获取应用的商户渠道配置列表
 * 配置类型：APP_MERCHANT_CHANNEL (config_type = 2)
 * 拥有者类型：APPLICATION (owner_type = 2)
 * 连接模式：存储应用的原始connectMode (DIRECT=1, INDIRECT=2)
 */
export const getAppChannelConfigs = async (params: AppChannelConfigQueryParams) => {
  try {
    console.log(`[API] 🔍 查询应用商户渠道配置 - 应用ID: ${params.appId}`)

    // 使用大页面确保获取所有数据
    const queryParams = {
      pageNumber: 1,
      pageSize: 1000,
      configType: 2, // APP_MERCHANT_CHANNEL
      ownerType: 2,   // APPLICATION
      ownerId: params.appId, // 按应用ID筛选
      channelCode: params.channelCode,
      enabled: params.enabled
    }

    const response = await apiUnifiedChannelConfigFetchList(queryParams)

    console.log(`[API] 📊 原始查询结果:`, {
      应用ID: params.appId,
      返回总数: response.data?.total || 0,
      记录数量: response.data?.records?.length || 0,
      分页信息: {
        current: response.data?.current,
        size: response.data?.size,
        pages: response.data?.pages
      }
    })

    // 严格验证数据归属，防止数据串
    const allRecords = response.data?.records || []
    const validConfigs = allRecords.filter((record: any) => {
      const isValidOwner = record.ownerId === params.appId
      const isValidType = record.ownerType === 2 && record.configType === 2

      if (!isValidOwner) {
        // console.warn(`[API] ⚠️ 发现数据串! 配置 ${record.configId} 属于应用 ${record.ownerId}，但查询的是 ${params.appId}`)
      }

      if (!isValidType) {
        // console.warn(`[API] ⚠️ 发现类型错误! 配置 ${record.configId} 类型: ${record.configType}/${record.ownerType}`)
      }

      return isValidOwner && isValidType
    })

    // 转换数据格式
    let configs = validConfigs.map((record: any) => ({
      configId: record.configId,
      configType: record.configType,
      ownerId: record.ownerId,
      ownerType: record.ownerType,
      channelCode: record.channelCode,
      productCode: record.productCode,
      connectMode: record.connectMode,
      configData: record.configData,
      enabled: record.enabled,
      createdTime: record.createdTime,
      updatedTime: record.updatedTime
    }))

    // 如果指定了channelCode，在客户端进行额外过滤
    if (params.channelCode) {
      const beforeFilter = configs.length
      configs = configs.filter((config: any) => config.channelCode === params.channelCode)
      console.log(`[API] 🔍 渠道过滤: ${params.channelCode}, 过滤前: ${beforeFilter}, 过滤后: ${configs.length}`)
    }

    // 如果指定了connectMode，在客户端进行额外过滤
    if (params.connectMode) {
      const beforeFilter = configs.length
      configs = configs.filter((config: any) => config.connectMode === params.connectMode)
      console.log(`[API] 🔍 连接模式过滤: ${params.connectMode}, 过滤前: ${beforeFilter}, 过滤后: ${configs.length}`)
    }

    console.log(`[API] ✅ 最终有效配置数量: ${configs.length}`, {
      应用: params.appId,
      渠道: params.channelCode || '全部',
      连接模式: params.connectMode || '全部',
      配置列表: configs.map((cfg: any) => ({
        configId: cfg.configId,
        channelCode: cfg.channelCode,
        connectMode: cfg.connectMode,
        enabled: cfg.enabled
      }))
    })

    return {
      success: true,
      data: configs,
      total: configs.length
    }
  } catch (error) {
    console.error(`[API] ❌ 获取应用 ${params.appId} 商户渠道配置失败:`, error)
    throw error
  }
}

/**
 * 保存应用商户渠道配置
 * 配置类型：APP_MERCHANT_CHANNEL (config_type = 2)
 * 拥有者类型：APPLICATION (owner_type = 2)
 */
export const saveAppChannelConfig = async (configData: AppChannelConfigData) => {
  try {
    console.log(`[API] 💾 保存应用商户渠道配置 - 应用: ${configData.ownerId}, 渠道: ${configData.channelCode}, 模式: ${configData.connectMode}`)

    // 使用三个条件查询确保精确匹配：appId + channelCode + connectMode
    const existingResponse = await getAppChannelConfigs({
      appId: configData.ownerId,
      channelCode: configData.channelCode,
      connectMode: configData.connectMode
    })

    const exists = existingResponse.data && existingResponse.data.length > 0
    const existingConfig = exists ? existingResponse.data[0] : null

    console.log(`[API] 🔍 配置检查结果:`, {
      存在: exists,
      现有配置ID: existingConfig?.configId,
      操作类型: exists ? '更新' : '新增'
    })

    // 严格的数据验证
    if (exists && existingConfig && existingConfig.ownerId !== configData.ownerId) {
      throw new Error(`数据归属错误: 现有配置属于应用 ${existingConfig.ownerId}，但尝试以应用 ${configData.ownerId} 身份保存`)
    }

    // 准备保存的数据
    const saveData: any = {
      configType: 2, // APP_MERCHANT_CHANNEL
      ownerId: configData.ownerId, // 应用ID
      ownerType: 2, // APPLICATION
      channelCode: configData.channelCode,
      productCode: configData.productCode || '',
      connectMode: configData.connectMode,
      configData: typeof configData.configData === 'string'
        ? configData.configData
        : JSON.stringify(configData.configData || {}),
      enabled: configData.enabled ?? false
    }

    // 只有在更新现有配置时才传递configId
    if (exists && existingConfig) {
      saveData.configId = existingConfig.configId
    }
    // 新建配置时不传递configId，让后端自动生成

    console.log(`[API] 📝 准备保存数据:`, {
      configId: saveData.configId,
      configType: saveData.configType,
      ownerId: saveData.ownerId,
      ownerType: saveData.ownerType,
      channelCode: saveData.channelCode,
      connectMode: saveData.connectMode,
      enabled: saveData.enabled,
      操作: exists ? '更新' : '新增'
    })

    console.log(`[API] 🔍 完整保存数据:`, saveData)

    let response: any
    if (exists && existingConfig) {
      // 更新现有配置
      console.log(`[API] 🔄 更新配置: ${existingConfig.configId}`)
      response = await apiUnifiedChannelConfigEdit(existingConfig.configId, saveData)
    } else {
      // 创建新配置 - 使用UCC专用接口确保生成正确的UCC ID
      console.log(`[API] ➕ 创建新配置，调用UCC专用接口`)
      response = await apiUnifiedChannelConfigCreateUcc(saveData)
    }

    const message = exists ? '配置更新成功' : '配置创建成功'
    console.log(`[API] ✅ ${message}`, {
      configId: response.data?.configId || saveData.configId,
      应用: configData.ownerId,
      渠道: configData.channelCode,
      连接模式: configData.connectMode
    })

    return {
      success: true,
      data: response.data,
      message: message
    }
  } catch (error) {
    console.error(`[API] ❌ 保存应用渠道配置失败:`, {
      应用: configData.ownerId,
      渠道: configData.channelCode,
      连接模式: configData.connectMode,
      错误: error
    })
    throw error
  }
}

/**
 * 更新应用渠道启用状态
 */
export const updateAppChannelStatus = async (appId: string, channelCode: string, connectMode: number, enabled: boolean) => {
  try {
    console.log(`[API] 🔄 更新应用渠道状态 - 应用: ${appId}, 渠道: ${channelCode}, 模式: ${connectMode}, 状态: ${enabled ? '启用' : '禁用'}`)

    // 使用三个条件查询确保精确匹配
    const existingResponse = await getAppChannelConfigs({
      appId,
      channelCode,
      connectMode
    })

    if (!existingResponse.data || existingResponse.data.length === 0) {
      throw new Error(`渠道配置不存在: 应用 ${appId}, 渠道 ${channelCode}, 模式 ${connectMode}`)
    }

    const config = existingResponse.data[0]

    // 严格的权限验证
    if (config.ownerId !== appId) {
      throw new Error(`权限错误: 配置属于应用 ${config.ownerId}，但尝试以应用 ${appId} 身份操作`)
    }

    console.log(`[API] 🔍 找到配置:`, {
      configId: config.configId,
      当前状态: config.enabled,
      目标状态: enabled
    })

    const updateData = {
      ...config,
      enabled,
      updatedTime: new Date().toISOString()
    }

    const response: any = await apiUnifiedChannelConfigEdit(config.configId, updateData)

    const message = `渠道${enabled ? '启用' : '禁用'}成功`
    console.log(`[API] ✅ ${message}`, {
      configId: config.configId,
      应用: appId,
      渠道: channelCode,
      连接模式: connectMode,
      状态: enabled
    })

    return {
      success: true,
      data: response.data,
      message: message
    }
  } catch (error) {
    console.error(`[API] ❌ 更新应用渠道状态失败:`, {
      应用: appId,
      渠道: channelCode,
      连接模式: connectMode,
      目标状态: enabled,
      错误: error
    })
    throw error
  }
}

/**
 * 测试应用渠道连接
 */
export const testAppChannelConnection = async (appId: string, channelCode: string, connectMode: number) => {
  try {
    console.log(`[API] 🧪 测试应用渠道连接 - 应用: ${appId}, 渠道: ${channelCode}, 模式: ${connectMode}`)

    // 这里可以调用实际的测试接口
    // 目前返回模拟成功结果
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟网络延迟

    return {
      success: true,
      message: '连接测试成功'
    }
  } catch (error) {
    console.error('测试应用渠道连接失败:', error)
    throw error
  }
}